const wechat = require('wechat');
const express = require('express');
const wechatApi = require('utils/wechat_api.js');
const mongoose = require('utils/mongoose.js');

const config = require('../config.js');
const constant = require('utils/constant.js');

const User = require('./models/User.js');

// const filepath = '/Users/huang/Desktop/APP/wechat/wechat_adj/wechat/routes/default.jpg';
var func = wechat(config, function (req, res, next) {

	let msg = req.weixin;

	// 最高优先级逻辑，不受活动控制
	handleHighPriorityMsg(msg, req, res);

	

	//TODO 日常逻辑
	let ret = false;
	if (msg.MsgType == constant.msgType.text) {
		ret = handleTextMsg(msg, req, res);
	} else if (msg.MsgType == constant.msgType.voice) {
		ret = handleVoiceMsg(msg, req, res);
	} else if (msg.MsgType == constant.msgType.video) {
		ret = handleVideoMsg(msg, req, res);
	} else if (msg.MsgType == constant.msgType.image) {
		ret = handleImageMsg(msg, req, res);
	} else if (msg.MsgType == constant.msgType.event) {
		ret = handleEventMsg(msg, req, res);
	}

	if(!ret){
		//处理不了的消息，空回复，保证公众号不会有错误提示！
		res.reply('你好这里是童年玩具屋，我们将为您推送高质量的玩具视频~');
	}

});

/***以下一系列handle方法，如果能处理消息，那么返回true，不能则返回false***/

function handleTextMsg(msg, req, res) {
	return false;
}

function handleVoiceMsg(msg, req, res) {
	return false;
}

function handleVideoMsg(msg, req, res) {
	return false;
}

function handleEventMsg(msg, req, res) {
	if(msg.Event == 'subscribe') {
		res.reply('欢迎关注童年玩具屋，童年玩具屋新春活动童装送礼活动已经于2017年1月14号 23:59:59结束咯！');
		return true;
	}
	return false;
}

function handleImageMsg(msg, req, res) {
	return false;
}

//特殊方法
function handleHighPriorityMsg(msg, req, res, retryFlag) {
	if(msg.MsgType == constant.msgType.event &&
		msg.Event == 'subscribe') {

		User.findOne({'openid':msg.FromUserName}).exec(function(err, user){
			if(err) {
				console.log('find user err : ' + err);
			} else if(!user) {
				wechatApi.getUser(msg.FromUserName,function(err, info) {
					if(err) {
						if(typeof retryFlag == 'undefined') {
							console.log('getUser info fail : ' + err);
							handleHighPriorityMsg(msg, req, res, true);
						} else {
							console.log('【retry】getUser info fail : ' + err);
						}
					} else {
						var user =  new User(info);
						user.save(function(err, doc){
							if(err) {
								console.log('save user fail : ' + err);
							} else {
								console.log('save user succssful，info : ' + doc);
							}
						});
					}
				});
			}
		});
	}
}

/***********************handle 方法结束****************************/


module.exports = func;
